<template>
	<view class="home">
		<view class="bg"></view>
		<view class="main">
			<view class="body">
				<view class="form">
					<view class="notice-bar">
						<uv-notice-bar text="为保障您的合法权益,请线上完成订单"></uv-notice-bar>
					</view>
					<scroll-view scroll-x>
						<view class="swiper">
							<view
								v-for="(jobType, index) in jobTypeList"
								:key="jobType._id"
								:class="['swiper-item', query.job_type_id == jobType._id ? 'active' : '']"
								@click="handleChangeJobType(jobType)"
							>
								<view class="job-type-logo">
									<image class="image" :src="jobType.logo.url"></image>
								</view>
								<view class="name">{{ jobType.name }}</view>
								<view class="label">{{ jobType.work_time }}</view>
							</view>
						</view>
					</scroll-view>
					<uv-cell-group :border="false">
						<uv-cell isLink :label="query.employment_time || '请选择用工时间'" @click="selectDateShow = true">
							<template #label>
								<view v-if="query.employment_time" class="cell-label">
									{{ dayjs(query.employment_time).format("YYYY-MM-DD HH:mm") }}
								</view>
								<view v-else class="cell-label">请选择用工时间</view>
							</template>
							<template #icon>
								<view class="cell-icon">
									<uni-icons custom-prefix="iconfont" type="icon-time" size="18" color="#00ae66"></uni-icons>
								</view>
							</template>
						</uv-cell>
						<uv-cell isLink :label="query.address || '请选择用工地址'" @click="toSelectLocation">
							<template #icon>
								<view class="cell-icon">
									<uni-icons type="map" size="18" color="#f6d44c"></uni-icons>
								</view>
							</template>
						</uv-cell>
						<uv-cell>
							<template #label>
								<uv-input
									v-model="query.need_tool"
									border="none"
									placeholder="需带工具(选填)"
									prefix-icon="question-circle"
									:prefixIconStyle="{ color: '#ccc' }"
								></uv-input>
							</template>
						</uv-cell>
						<uv-cell>
							<template #label>
								<uv-input
									v-model="query.male_numbers"
									border="none"
									placeholder="男工人数"
									prefix-icon="man"
									type="number"
									:prefixIconStyle="{ color: 'skyblue' }"
								></uv-input>
							</template>
						</uv-cell>
						<uv-cell>
							<template #label>
								<uv-input
									v-model="query.female_numbers"
									border="none"
									placeholder="女工人数"
									prefix-icon="woman"
									type="number"
									:prefixIconStyle="{ color: 'pink' }"
								></uv-input>
							</template>
						</uv-cell>
						<uv-cell label="预估金额" :value="`￥${total}`"></uv-cell>
					</uv-cell-group>
					<view class="next-btn">
						<uv-button text="支付并叫工" type="warning" shape="circle" @click="handleToLaunchOrder"></uv-button>
					</view>
				</view>
				<view class="notice">
					<swiper autoplay vertical :duration="1000">
						<swiper-item v-for="(notice, index) in noticeList" :key="index">
							<view class="notice-item">
								<uv-avatar></uv-avatar>
								<view>{{ notice.name }}</view>
								<view>{{ notice.job_type_name }}</view>
								<view>{{ notice.status == 1 ? "已完成" : "进行中" }}</view>
								<view>{{ notice.date }}</view>
								<view>
									<uv-rate :value="notice.rate" readonly active-color="#fcca00"></uv-rate>
								</view>
							</view>
						</swiper-item>
					</swiper>
				</view>
				<view class="advantage">
					<view class="item">
						<image class="image" src="/static/images/a-30.png"></image>
						<view class="text">30秒接单</view>
					</view>
					<view class="item">
						<image class="image" src="/static/images/a-jj.png"></image>
						<view class="text">就近派工</view>
					</view>
					<view class="item">
						<image class="image" src="/static/images/a-cj.png"></image>
						<view class="text">自己出价</view>
					</view>
					<view class="item">
						<image class="image" src="/static/images/a-fp.png"></image>
						<view class="text">正规发票</view>
					</view>
				</view>
				<view class="tabs">
					<uv-tabs :current="currentTabIndex" line-color="#f6d44c" :list="tabList" @change="handleTabChange"></uv-tabs>
				</view>
				<view class="bottom">
					<template v-if="currentTabIndex == 0">
						<view class="evaluate-list">
							<template v-for="(evalate, index) in evaluateList" :key="index">
								<evaluate
									:avatar="evalate.avatar"
									:name="evalate.phone"
									:ip="evalate.ip"
									:rate="evalate.rate"
									:date="evalate.date"
									:content="evalate.content"
								></evaluate>
							</template>
						</view>
					</template>
					<template v-if="currentTabIndex == 1">
						<view class="cooperation">
							<view class="please">请扫码添加微信</view>
							<image show-menu-by-longpress class="image" src="/static/images/commerce-qrcode.png"></image>
							<view class="tips">长摁识别二维码</view>
						</view>
					</template>
				</view>
			</view>
		</view>
		<uv-datetime-picker
			ref="uvDatetimePickerRef"
			title="选择时间"
			round="10"
			:min-date="minDate"
			:max-date="maxDate"
			:formatter="datePickerFormatter"
			:filter="datePickerFilter"
			@confirm="handleDatePickerConfirm"
		></uv-datetime-picker>
		<select-date v-model:visible="selectDateShow" v-model:value="query.employment_time"></select-date>
		<uni-pay ref="uniPayRef" mainColor="#f6d44c" returnUrl="/pages/order-details/order-details"></uni-pay>
	</view>
</template>

<script setup>
import { onReady } from "@dcloudio/uni-app";
import { ref, watch, computed } from "vue";
import createOrderNo from "@/utils/createOrderNo";
import objectToUrl from "../../utils/objectToUrl";
import dayjs from "dayjs";
import { useUserStore } from "../../store/user";

// 男工单日价格
const maleAmount = 0.02;

// 女工单日价格
const femaleAmount = 0.01;

const db = uniCloud.database();

const uvDatetimePickerRef = ref();

const uniPayRef = ref();

const minDate = Date.now();
const maxDate = Date.now() + 1000 * 60 * 60 * 24 * 30;

const selectDateShow = ref(false);

const city = ref({
	code: "",
	name: "请选择城市"
});

const noticeList = [
	{
		avatar: "",
		name: "田治龙",
		job_type_name: "绿化工",
		status: 1,
		date: "5-6",
		rate: 5
	},
	{
		avatar: "",
		name: "张超",
		job_type_name: "绿化工",
		status: 1,
		date: "5-6",
		rate: 5
	},
	{
		avatar: "",
		name: "马召波",
		job_type_name: "绿化工",
		status: 1,
		date: "5-6",
		rate: 5
	}
];

const tabList = [
	{
		name: "客户评价"
	},
	{
		name: "企业合作"
	}
];

const evaluateList = [
	{
		avatar: "",
		phone: "177638232105",
		rate: 5,
		ip: "杭州市",
		date: "2024-05-07",
		content: "王师傅很给力,20层楼十多张大板,上楼梯完成, 给五星好评,人很不错,需要朋友可以找他帮忙,感 谢王师傅鼎立相助。"
	},
	{
		avatar: "",
		phone: "177638232105",
		rate: 5,
		ip: "杭州市",
		date: "2024-05-07",
		content: "王师傅很给力,20层楼十多张大板,上楼梯完成, 给五星好评,人很不错,需要朋友可以找他帮忙,感 谢王师傅鼎立相助。"
	}
];

const jobTypeList = ref([]);
const currentTabIndex = ref(0);
const query = ref({
	job_type_id: "",
	employment_time: "",
	address: "",
	longitude: "",
	latitude: "",
	// house_number: "",
	male_numbers: "",
	female_numbers: "",
	need_tool: "",
	user_id: uni.getStorageSync("uni-id-pages-userInfo")._id,
	longitude: "",
	latitude: "",
	// house_number: "",
	charging_mode: 1,
	offer: 100,
	supplement: "",
	images: [],
	require_work_time: 1,
	charging_unit: 1,
	order_no: ""
});

// 总价
const total = computed(() => {
	let totalFee = 0;
	totalFee += query.value.male_numbers * maleAmount;
	totalFee += query.value.female_numbers * femaleAmount;
	if (totalFee > 1000) {
		return Number((totalFee * 1.05).toFixed(2));
	} else {
		return Number((totalFee * 1.08).toFixed(2));
	}
});

// 获取工种类型
const getJobTypeList = async () => {
	const response = await db.collection("job-type").get();
	console.log(response);
	if (response.result && response.result.code == 0) {
		jobTypeList.value = response.result.data;
		query.value.job_type_id = response.result.data[0]._id;
	}
};

// 选择工种类型
const handleChangeJobType = (value) => {
	query.value.job_type_id = value._id;
};

// 日期选择格式化
const datePickerFormatter = (type, value) => {
	if (type === "year") {
		return `${value}年`;
	}
	if (type === "month") {
		return `${value}月`;
	}
	if (type === "day") {
		return `${value}日`;
	}
	if (type == "hour") {
		return `${value}时`;
	}
	if (type == "minute") {
		return `${value}分`;
	}
	return value;
};

// 打开日期选择
const handleOpenDatePicker = () => {
	uni.showModal({
		title: "提示",
		content: "请选择时间",
		cancelText: "预约",
		confirmText: "现在用工",
		success: (res) => {
			if (res.confirm) {
				query.value.employment_time = dayjs(Date.now()).format("YYYY-MM-DD HH:mm");
			}
			if (res.cancel) {
				uvDatetimePickerRef.value.open();
			}
		}
	});
};

// 选择日期
const handleDatePickerConfirm = (event) => {
	console.log(new Date(event.value).toLocaleString());
	query.value.employment_time = event.value;
};

// 跳转选择地址
const toSelectLocation = () => {
	uni.chooseLocation({
		success: (event) => {
			query.value.address = event.address;
			query.value.longitude = event.longitude;
			query.value.latitude = event.latitude;
		}
	});
};

const userStore = useUserStore();

// 前往发起订单页面
const handleToLaunchOrder = () => {
	if (!userStore.isLogin) {
		return uni.showModal({
			title: "提示",
			content: "请先进行登录",
			success: (res) => {
				if (res.confirm) {
					uni.navigateTo({
						url: "/uni_modules/uni-id-pages/pages/login/login-withpwd"
					});
				}
			}
		});
	}
	if (!query.value.job_type_id) {
		uni.showToast({
			title: "请选择工种类型",
			icon: "none"
		});
	} else if (!query.value.employment_time) {
		uni.showToast({
			title: "请选择用工时间",
			icon: "none"
		});
	} else if (!query.value.address) {
		uni.showToast({
			title: "请选择用工地址",
			icon: "none"
		});
	} else if (!Number(query.value.male_numbers) && !Number(query.value.female_numbers)) {
		uni.showToast({
			title: "请选择用工人数",
			icon: "none"
		});
	} else {
		// const params = objectToUrl(query.value);
		// uni.navigateTo({
		// 	url: "/pages/launch-order/launch-order" + params
		// });
		query.value.offer = Number(query.value.offer);
		query.value.require_work_time = Number(query.value.require_work_time);
		query.value.order_no = createOrderNo();
		const out_trade_no = `${query.value.order_no}-trade`;
		const total_fee = Number((total.value * 100).toFixed(0));
		console.log(total_fee);
		uniPayRef.value.open({
			total_fee: 1,
			order_no: query.value.order_no,
			out_trade_no,
			description: `景元用工订单`,
			type: "goods",
			custom: query.value
		});
	}
};

// 底部tab change 事件
const handleTabChange = (event) => {
	currentTabIndex.value = event.index;
};

onReady(async () => {
	await getJobTypeList();
});
</script>

<style lang="scss" scoped>
.home {
	height: 100%;
	position: relative;
	background-color: #f4f5f9;
	overflow: scroll;

	.bg {
		background: linear-gradient(to top, #f4f5f9, #f6d44c);
		height: 250px;
	}

	.main {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		display: flex;
		flex-direction: column;
		padding: 20px;
		box-sizing: border-box;

		.top {
			display: flex;
			justify-content: center;
			align-items: center;
			margin-bottom: 20px;

			.item {
			}

			.logo {
				display: flex;
				align-items: center;
				filter: brightness(0.1);
				image {
					width: 60px;
					height: 60px;
				}
				text {
					font-size: 24px;
					color: #4ba659;
				}
			}
		}

		.form {
			background-color: #ffffff;
			padding: 20px;
			border-radius: 10px;

			.notice-bar {
				margin-bottom: 20px;
			}

			.swiper {
				display: flex;
				justify-content: center;
				align-items: center;
				gap: 20px;
				padding-bottom: 20px;

				.swiper-item {
					.job-type-logo {
						display: flex;
						justify-content: center;
					}
					&.active {
						color: $uni-color-primary;
						.image {
							border: 5px solid $uni-color-primary;
							border-radius: 120px;
							width: 120px;
							height: 120px;
						}
					}

					.image {
						border-radius: 100px;
						width: 100px;
						height: 100px;
						margin-bottom: 10px;
					}
					.name {
						font-size: 18px;
						text-align: center;
					}
				}
			}

			.cell-icon {
				margin-left: 5px;
				display: flex;
				align-items: center;
			}

			.cell-label {
				font-size: 12px;
				color: #909193;
			}

			.next-btn {
				margin-top: 20px;
			}
		}

		.notice {
			margin-top: 20px;
			swiper {
				height: 50px;
			}

			.notice-item {
				font-size: 12px;
				display: flex;
				align-items: center;
				justify-content: space-between;
			}
		}

		.advantage {
			margin-top: 20px;
			display: flex;
			align-items: center;
			justify-content: space-between;
			text-align: center;
			background-color: #ffffff;
			padding: 20px;
			border-radius: 10px;

			.image {
				width: 30px;
				height: 30px;
			}
			.text {
				margin-top: 10px;
				font-size: 14px;
			}
		}

		.tabs {
			margin-top: 20px;
			background: linear-gradient(to bottom, #ffffff, #f4f5f9);
			padding: 10px;
		}

		.bottom {
			margin-bottom: 20px;

			.cooperation {
				margin-top: 20px;
				text-align: center;

				.please {
					font-size: 18px;
					margin-bottom: 20px;
				}

				.image {
					width: 200px;
					height: 200px;
				}

				.tips {
					font-size: 14px;
					color: #666666;
				}
			}
		}
	}
}
</style>
